/// Copyright (c) Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Microsoft.VSPowerToys.Common.TaskManager
{
    /// <summary>
    /// A task to install apps that have a setup.exe style installer. Task throws InstallExeException in case
    /// of an error.
    /// </summary>
    public class InstallExeTask : WindowsInstallerTask
    {      
        #region Constructors

        /// <summary>
        /// Creates a new EXE installation task for the specified installer
        /// </summary>
        /// <param name="location">Full path to EXE file to install</param>
        public InstallExeTask(string location)
            : base(location)
        {
        }
        
        #endregion

        public override void PerformTask()
        {
            if (!File.Exists(this.InstallerLocation))
            {
                throw new TaskException("EXE file could not be found", null, this);
            }
            StringBuilder arguments = new StringBuilder();
            if (this.RunInSilentMode)
            {
                arguments.Append(" /quiet /norestart");
            }

            foreach (string key in this.Parameters.Keys)
            {
                arguments.Append(" " + key + "=\"" + this.Parameters[key] + "\"");
            }

            int returnCode =0;
            try
            {
                Process toolInstallProcess = Process.Start(this.InstallerLocation, arguments.ToString());
                toolInstallProcess.WaitForExit();
                returnCode = toolInstallProcess.ExitCode;
            } 
            catch (System.ComponentModel.Win32Exception ex) 
            {
                throw new TaskException("Unknown error occured", ex, this);
            }
            switch (returnCode)
            {
                case 0:
                    return;
                default:
                    throw new ExeException(this.InstallerLocation, returnCode, this);
            }
        }
    }
}